import React, { useState, useEffect } from 'react';
import { Button, Table, Tag, notification, Space, Alert, Modal, Tooltip, Descriptions, Card } from 'antd';
import { useNavigate } from 'react-router-dom';
import { SyncOutlined, EditOutlined, CheckCircleOutlined, RollbackOutlined, ExclamationCircleOutlined, EyeOutlined } from '@ant-design/icons';
import { useMyAuditList, useSubmitNews } from '../../../hooks/useNewsManage';
import useSimpleAuth from '../../../hooks/useSimpleAuth';
import RegionBadge from '../../../components/common/RegionBadge';
import SimplePermissionButton from '../../../components/permission/SimplePermissionButton';
import { News, AuditState, PublishState } from '../../../types';
import { updateNewsState } from '../../../api/newsApi';
import './Audit.scss';

const { confirm } = Modal;

// 审核状态对应的标签
const auditStateMap: Record<number, { color: string; text: string; icon: React.ReactNode }> = {
  0: { color: 'default', text: '草稿', icon: <EditOutlined /> },
  1: { color: 'processing', text: '审核中', icon: <SyncOutlined spin /> },
  2: { color: 'success', text: '已通过', icon: <CheckCircleOutlined /> },
  3: { color: 'error', text: '未通过', icon: <ExclamationCircleOutlined /> }
};

const AuditList: React.FC = () => {
  const navigate = useNavigate();
  const [previewNews, setPreviewNews] = useState<News | null>(null);
  const [previewVisible, setPreviewVisible] = useState(false);
  
  // 使用简化版权限钩子
  const { filterNewsByDepartment } = useSimpleAuth();
  
  // 使用钩子获取用户信息
  const username = getUserUsername();
  
  // 获取当前用户提交的审核列表
  const { data: myAuditList = [], isLoading, refetch } = useMyAuditList(username || '');
  
  // 组件挂载时刷新数据
  useEffect(() => {
    console.log('AuditList组件挂载，刷新审核列表...');
    refetch();
  }, [refetch]);
  
  // 获取用户名函数 - 从localStorage获取，确保组件能够渲染
  function getUserUsername(): string {
    try {
      const userInfoStr = localStorage.getItem('userInfo');
      if (!userInfoStr) return '';
      const userInfo = JSON.parse(userInfoStr);
      return userInfo.username || '';
    } catch (error) {
      console.error('获取用户名失败:', error);
      return '';
    }
  }
  
  // 过滤后的数据
  const filteredAuditList = React.useMemo(() => {
    try {
      // 确保myAuditList是数组
      const newsArray = Array.isArray(myAuditList) ? myAuditList : [];
      console.log('审核列表数据更新，过滤前数量:', newsArray.length);
      
      // 使用钩子中的方法，现在已经正确包装了auth方法
      const filtered = filterNewsByDepartment(newsArray);
      console.log('审核列表过滤后数量:', filtered.length);
      return filtered;
    } catch (error) {
      console.error('过滤新闻列表失败:', error);
      return [];
    }
  }, [myAuditList, filterNewsByDepartment]);
  
  // 撤回审核
  const submitNewsMutation = useSubmitNews();
  
  // 格式化时间
  const formatTime = (time?: number | string | Date) => {
    if (!time) return '未知时间';
    return new Date(time).toLocaleString();
  };
  
  // 预览新闻
  const handlePreview = (item: News) => {
    setPreviewNews(item);
    setPreviewVisible(true);
  };
  
  // 撤回审核
  const handleRevert = (item: News) => {
    const newsId = item._id || item.id || item.seqId || '';
    
    // 检查是否是自己的新闻
    if (item.author !== username) {
      notification.error({
        message: '操作失败',
        description: '您只能操作自己的新闻',
        placement: 'bottomRight'
      });
      return;
    }
    
    confirm({
      title: '确认撤回',
      icon: <ExclamationCircleOutlined />,
      content: '撤回后，新闻将回到草稿箱状态，需要重新提交审核',
      okText: '确认撤回',
      cancelText: '取消',
      onOk() {
        submitNewsMutation.mutate(newsId, {
          onSuccess: () => {
            notification.success({
              message: '撤回成功',
              description: `您已成功撤回《${item.title}》，可以在草稿箱中查看`,
              placement: 'bottomRight'
            });
            
            // 立即刷新获取最新数据
            setTimeout(() => {
              refetch();
            }, 300);
          }
        });
      }
    });
  };
  
  // 更新修改
  const handleUpdate = (item: News) => {
    // 检查是否是自己的新闻
    if (item.author !== username) {
      notification.error({
        message: '操作失败',
        description: '您只能操作自己的新闻',
        placement: 'bottomRight'
      });
      return;
    }
    
    const newsId = item._id || item.id || item.seqId || '';
    navigate(`/news-manage/add/${newsId}`);
  };
  
  // 发布新闻（先设置为待发布状态，再导航到待发布列表）
  const handlePublish = async (item: News) => {
    try {
      // 获取新闻ID
      const newsId = item._id || item.id || item.seqId || '';
      console.log(`准备将新闻ID=${newsId}设置为待发布状态`);
      
      // 1. 先将新闻设置为待发布状态 (publishState=1)
      await updateNewsState(newsId, {
        publishState: PublishState.PENDING // 值为1, 待发布状态
      });
      
      // 执行发布后立即刷新数据
      setTimeout(() => {
        refetch();
      }, 300);
      
      // 2. 然后导航到待发布列表
      navigate(`/publish-manage/unpublished`);
      notification.success({
        message: '新闻已设置为待发布状态',
        description: '您可以在发布管理/待发布中发布该新闻',
        placement: 'bottomRight'
      });
    } catch (error) {
      console.error('设置待发布状态失败:', error);
      notification.error({
        message: '操作失败',
        description: '无法设置新闻为待发布状态',
        placement: 'bottomRight'
      });
    }
  };
  
  const columns = [
    {
      title: 'ID',
      dataIndex: 'seqId',
      width: 80
    },
    {
      title: '新闻标题',
      dataIndex: 'title',
      ellipsis: true,
      width: 300,
      render: (title: string, item: News) => {
        const newsId = item._id || item.id || item.seqId || '';
        return <a onClick={() => navigate(`/news-manage/preview/${newsId}`)}>{title}</a>;
      }
    },
    {
      title: '作者',
      dataIndex: 'author',
      width: 100
    },
    {
      title: '部门',
      dataIndex: 'region',
      width: 120,
      render: (region: string) => <RegionBadge region={region} />
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      width: 120,
      render: (category: { title: string } | undefined) => category?.title || '未分类'
    },
    {
      title: '提交时间',
      dataIndex: 'createTime',
      width: 180,
      render: (time: number | string | Date) => formatTime(time),
      sorter: (a: News, b: News) => {
        // 修复TypeScript错误，安全处理时间比较
        const timeA = typeof a.createTime === 'object' && a.createTime !== null ? 
          (a.createTime as Date).getTime() : Number(a.createTime);
        const timeB = typeof b.createTime === 'object' && b.createTime !== null ? 
          (b.createTime as Date).getTime() : Number(b.createTime);
        return timeA - timeB;
      }
    },
    {
      title: '审核状态',
      dataIndex: 'auditState',
      width: 120,
      render: (auditState: AuditState, record: News) => {
        const { color, text, icon } = auditStateMap[auditState] || { color: 'default', text: '未知状态', icon: null };
        let content = <Tag color={color} icon={icon}>{text}</Tag>;
        
        // 审核拒绝时显示拒绝原因
        if (auditState === AuditState.REJECTED && (record.reason || record.auditReason)) {
          content = (
            <Tooltip title={`拒绝原因: ${record.reason || record.auditReason || '未提供'}`}>
              {content}
            </Tooltip>
          );
        }
        
        return content;
      }
    },
    {
      title: '操作',
      width: 220,
      render: (_: unknown, item: News) => {
        // 只有本人的新闻才能操作
        const isMyNews = item.author === username;
        
        // 如果不是自己的新闻，只显示预览按钮
        if (!isMyNews) {
          return (
            <Tooltip title="预览">
              <Button icon={<EyeOutlined />} onClick={() => handlePreview(item)} />
            </Tooltip>
          );
        }
        
        if (item.auditState === AuditState.PENDING) {
          return (
            <Space size="small">
              <Tooltip title="预览">
                <Button icon={<EyeOutlined />} onClick={() => handlePreview(item)} />
              </Tooltip>
              <SimplePermissionButton 
                permission="revert.news.audit"
                icon={<RollbackOutlined />} 
                onClick={() => handleRevert(item)}
                tooltipTitle="撤回"
              >
                撤回
              </SimplePermissionButton>
            </Space>
          );
        }
        
        if (item.auditState === AuditState.APPROVED) {
          return (
            <Space size="small">
              <Tooltip title="预览">
                <Button icon={<EyeOutlined />} onClick={() => handlePreview(item)} />
              </Tooltip>
              <SimplePermissionButton 
                permission="publish.news"
                type="primary" 
                icon={<CheckCircleOutlined />} 
                onClick={() => handlePublish(item)}
                tooltipTitle="发布"
              >
                发布
              </SimplePermissionButton>
            </Space>
          );
        }
        
        if (item.auditState === AuditState.REJECTED) {
          return (
            <Space size="small">
              <Tooltip title="预览">
                <Button icon={<EyeOutlined />} onClick={() => handlePreview(item)} />
              </Tooltip>
              <SimplePermissionButton 
                permission="update.news"
                type="primary" 
                danger
                icon={<EditOutlined />} 
                onClick={() => handleUpdate(item)}
                tooltipTitle="修改"
              >
                修改
              </SimplePermissionButton>
            </Space>
          );
        }
        
        return null;
      }
    }
  ];
  
  // 生成预览内容
  const renderPreviewContent = () => {
    if (!previewNews) return null;
    
    return (
      <Card bordered={false}>
        <Descriptions title="新闻信息" bordered column={2} size="small">
          <Descriptions.Item label="标题" span={2}>{previewNews.title}</Descriptions.Item>
          <Descriptions.Item label="作者">{previewNews.author}</Descriptions.Item>
          <Descriptions.Item label="分类">{previewNews.category?.title || '未分类'}</Descriptions.Item>
          <Descriptions.Item label="区域">{previewNews.region || '全球'}</Descriptions.Item>
          <Descriptions.Item label="创建时间">{formatTime(previewNews.createTime)}</Descriptions.Item>
          <Descriptions.Item label="审核状态" span={2}>
            {auditStateMap[previewNews.auditState]?.text || '未知状态'}
            {previewNews.auditState === AuditState.REJECTED && 
              <span style={{ color: 'red', marginLeft: 8 }}>
                拒绝原因: {previewNews.reason || previewNews.auditReason || '未提供'}
              </span>
            }
          </Descriptions.Item>
        </Descriptions>
        
        <div style={{ marginTop: 16 }}>
          <Alert 
            message="预览功能显示的内容摘要，完整内容请点击查看详情" 
            type="info" 
            showIcon 
            style={{ marginBottom: 16 }} 
          />
          <div dangerouslySetInnerHTML={{ 
            __html: previewNews.content?.substring(0, 300) + '...' || '无内容' 
          }} />
        </div>
      </Card>
    );
  };
  
  return (
    <div className="audit-list">
      <h2>审核列表</h2>
      
      <Alert
        message="这里显示您提交的所有新闻的审核状态"
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />
      
      <Table 
        dataSource={filteredAuditList}
        columns={columns}
        pagination={{ 
          pageSize: 5,
          showTotal: (total) => `共 ${total} 条` 
        }}
        rowKey={record => String(record.seqId || record._id || record.id || '')}
        loading={isLoading}
        locale={{ emptyText: '暂无审核记录' }}
      />
      
      <Modal
        title="新闻预览"
        open={previewVisible}
        footer={[
          <Button key="view" type="primary" onClick={() => {
            const newsId = previewNews?._id || previewNews?.id || previewNews?.seqId || '';
            navigate(`/news-manage/preview/${newsId}`);
          }}>
            查看详情
          </Button>,
          <Button key="close" onClick={() => setPreviewVisible(false)}>
            关闭
          </Button>
        ]}
        onCancel={() => setPreviewVisible(false)}
        width={700}
      >
        {renderPreviewContent()}
      </Modal>
    </div>
  );
};

export default AuditList; 